<template>
  <div class="app-container">
    <el-button type="primary" @click="handleAdd">创建商品分类</el-button>

    <el-table :data="productCategoryList" style="width: 100%;margin-top:30px;" stripe>
      <el-table-column 
        prop="name" 
        align="center" 
        label="分类名称">
      </el-table-column>
      <!-- <el-table-column 
        prop="parent.name" 
        align="center" 
        label="父级分类">
      </el-table-column>
      <el-table-column 
        prop="level" 
        align="center" 
        label="层级">
      </el-table-column> -->

      <el-table-column 
        prop="productCount" 
        align="center" 
        label="商品数">
      </el-table-column>
      <el-table-column 
        align="center" 
        label="是否显示">
        <template slot-scope="scope">{{ scope.row.showStatus === 0 ? '否' : '是' }}</template>
      </el-table-column>
      <el-table-column 
        prop="description" 
        align="center" 
        label="描述">
      </el-table-column>

      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEdit(scope)">编辑</el-button>
          <el-button type="text" size="small" @click="handleStatus(scope)">{{ scope.row.showStatus === 0 ? '显示' : '隐藏' }}</el-button>
          <el-button type="text" size="small" @click="handleDelete(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="block">
        <span class="demonstration"></span>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total">
        </el-pagination>
    </div>

    <!-- 新增或编辑商品分类 -->
    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑商品分类':'创建商品分类'">
      <el-form :model="productCategory" label-width="80px" label-position="left">
        <el-form-item label="分类名称">
          <el-input v-model="productCategory.name" placeholder="菜单名称" />
        </el-form-item>
        <!-- <el-form-item label="父级分类">
          <el-select v-model="productCategory.parentId" placeholder="请选择">
            <el-option
              v-for="item in parentList"
              :key="item.id"
              :label="item.title"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="描述">
          <el-input
            v-model="productCategory.description"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="描述"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmSubmit">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import path from 'path'
import { deepClone } from '@/utils'
import { getProductCategories, getParentCategories, addProductCategory, getProductCategoryDetail, updateProductCategory, updateCategoryShowSatus, delProductCategory } from '@/api/product'

const defaultRole = {
  key: '',
  name: '',
  description: '',
  routes: []
}

export default {
  data() {
    return {
      productCategory: {
        id: '',
        name: '',
        description: '',
        parentId: ''
      },
      parentList: [],
      productCategoryList: [],
      dialogVisible: false,
      dialogType: 'new',
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      }
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  created() {
    // Mock: get all routes and roles list from server
    this.getProductCategories()
    // this.getParentCategories()
  },
  methods: {
    async getProductCategories() {
      const res = await getProductCategories(this.page)
      console.log("getProductCategories",res)
      // this.serviceRoutes = res.data
      const { pageNum, total, list } = res.data

      this.productCategoryList = list
      this.page.currentPage = pageNum
      this.page.total = total
    },
    // async getParentCategories() {
    //   const res = await getParentCategories()
    //   console.log("getParentList",res)
    //   this.parentList = res.data
    // },
    handleAdd() {
      // console.log("menu",this.menu)
      // console.log("menuAdd",this.menuAdd)
      this.productCategory = {}
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    async handleEdit(scope) {
      const res = await getProductCategoryDetail(scope.row.id)

      this.productCategory = res.data
      this.dialogType = 'edit'
      this.dialogVisible = true
    },
    handleStatus(scope) {
      const category = scope.row
      const status = category.showStatus === 0 ? '显示' : '隐藏'
      this.$confirm('确认'+status+category.name+'?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          if(status === '显示'){
            await updateCategoryShowSatus(category.id,1)
          }else{
            await updateCategoryShowSatus(category.id,0)
          }
          this.$message({
            type: 'success',
            message: status+category.name+'成功'
          })
          this.getProductCategories()
        })
        .catch(err => { console.error(err) })
    },
    handleDelete(scope) {
      this.$confirm('确认删除商品分类：'+scope.row.name+'?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await delProductCategory(scope.row.id).then(() => {
            this.$message({
              type: 'success',
              message: '删除菜单成功'
            })
          })

          this.getProductCategories()
        })
        .catch(() => { 
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
         })
    },

    async confirmSubmit() {
      const isEdit = this.dialogType === 'edit'

      if (isEdit) {
        await updateProductCategory(this.productCategory).then(() => {
          this.$message({
              type: 'success',
              message: '更新商品分类成功!'
            })
        })
      } else {
        await addProductCategory(this.productCategory).then(() => {
          this.$message({
              type: 'success',
              message: '创建商品分类成功!'
            })
        })
      }

      this.dialogVisible = false
      this.getProductCategories()

    },
    handleSizeChange() {
      console.log("handleSizeChange")
      this.getProductCategories()
    },
    handleCurrentChange() {
      console.log("handleCurrentChange")
      console.log("this.page",this.page)
      this.getProductCategories()

    },
    // reference: src/view/layout/components/Sidebar/SidebarItem.vue
    onlyOneShowingChild(children = [], parent) {
      let onlyOneChild = null
      const showingChildren = children.filter(item => !item.hidden)

      // When there is only one child route, the child route is displayed by default
      if (showingChildren.length === 1) {
        onlyOneChild = showingChildren[0]
        onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
        return onlyOneChild
      }

      // Show parent if there are no child route to display
      if (showingChildren.length === 0) {
        onlyOneChild = { ... parent, path: '', noShowingChildren: true }
        return onlyOneChild
      }

      return false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
